import { GenderType } from '../common/definition.js';
import { Util } from '../../utils/util.js';
import { MerchantCandidateMgr } from '../merchantOrg/merchantCandidateMgr.js';
import {
    getAccountOrgJoinData, getMerchantOrgActivePackageInfo, getPublicStore,
    getOrgSettings, getRetailSettings, getEmployeeDetailInfo, getAllStoreList,
    getTargetObjectData
} from '../../network/api.js';
import { AccountOrgJoinData } from '../merchantOrg/accountOrgJoinData.js';
import { MerchantActivePackage } from '../merchantOrg/merchantActivePackage.js';
import { NetworkParser, getApiData, DataPage } from '../../network/communicationConverter';
import { Store } from '../store/store.js';
import { TargetObject, TargetObjectFilter, TargetObjectPlatformType, TargetObjectType } from '../targetOrg/targetObject.js';
import { Definition } from '../common/definition.js';
import { OrgSettings } from '../merchantOrg/orgSettings.js';
import { MerchantRetailSettings } from '../retail/merchantRetailSettings.js';
import { Employee } from '../enterpriseMgt/employee.js';
import { PermissionInfo } from '../menus/permissionInfo.js';
import { StoreEmployeeRelation } from '../store/storeEmployee.js';
import { Engine } from '../engine.js';
import { TestConfig } from '../common/testConfig.js';
import { FundUiAction } from '../uiAction/fundUiAction.js';
import { TestSimulateData } from '../testMgr/testSimulateData.js';

// 用户账号类型枚举
export const UserAccountType = {
    PlatformAccount: 'PlatformAccount',     // 平台用户账号
    OrgInternalAccount: 'OrgInternalAccount' // 组织内部账号
};

export class Profile {
    constructor() {
        this.headImgUri = null;
        this._org = null; // 当前登录的商户对象（MerchantOrg 实例）

        this.id = '';
        this.userName = '';
        this.token = '';
        this.nickName = '';
        this.mobPhoneNum = '';
        this.rememberPwd = false;
        this.pwd = '';

        this.title = '';
        this.joinDate = null; // 可用 new Date() 或字符串表示时间
        this.email = '';
        this.gender = GenderType.unkown;
        this.needResetPwd = false;
        this.accountType = UserAccountType.PlatformAccount;
        this.createOrgId = '';
        this.enabled = true;

        this.wechatId = '';
        this.wechatNickName = '';
        this.wechatImgUrl = '';

        this.candidateOrg = null; // 可用组织 MerchantCandidateMgr

        this.accessAllStoreData = false; // 访问全局权限
        this.accessAllWarehouse = false; // 访问所有仓库

        //授权访问的门店
        this._storeList = [];   //List<StoreEmployeeRelation>

        this._permissionMgr = null; // 用户拥有的权限 PermissionInfo

        /// 当前门店 （包含所有门店虚拟门店）
        this.currentStore = null;
    }

    get storeList() {
        return this._storeList;
    }

    get storeListWithOutAllStore() {
        if (this._storeList.length === 0) {
            return [new StoreEmployeeRelation('', this.org.publicStore, new Employee(this.id))];
        }
        return this._storeList.filter(store => store.store.id !== '0');
    }

    /// 当前有效门店对象
    /// 如果当前时全部门店，则返回公共门店
    get getValideStore() {
        if (this.currentStore == null || this.currentStore.id == "0") {
            return this._org.publicStore;
        } else {
            return this.currentStore;
        }
    }

    /// 获取过滤 store信息
    /// currentStore 为所有门店不用过滤
    get filterStore() {
        if (this.currentStore != null) {
            if (this.currentStore.id == "0") {
                return null;
            }
        }

        return this.currentStore;
    }


    /// 权限
    get permissionMgr() { return this._permissionMgr; }

    get org() {
        return this._org;
    }

    // 从本地存储的 JSON 创建 Profile 实例
    static fromStoreJson(json) {
        const profile = new Profile();
        profile.userName = json.userName || '';
        profile.token = json.token || '';
        profile.rememberPwd = json.rd || false; // 'rd' 表示 rememberPwd 缩写
        profile.pwd = json.pwd || '';
        return profile;
    }

    // Create Profile instance from server JSON response
    static fromJson(json) {
        const profile = new Profile();

        profile.id = Util.jsonToString(json['accountId']);
        profile.userName = Util.jsonToString(json['loginName']);
        profile.nickName = Util.jsonToString(json['nickName']);
        profile.token = Util.jsonToString(json['token']);
        profile.mobPhoneNum = Util.jsonToString(json['phoneNum']);

        // Handle account type conversion
        profile.accountType = json['accType'] == null
            ? UserAccountType.PlatformAccount
            : (json['accType'] == '0'
                ? UserAccountType.PlatformAccount
                : UserAccountType.OrgInternalAccount);

        profile.createOrgId = Util.jsonToString(json['createOrgId']);
        profile.enabled = Util.jsonToBool(json['status'], false);

        profile.wechatId = Util.jsonToString(json['wxOpenId']);
        profile.wechatNickName = Util.jsonToString(json['wxNickName']);
        profile.wechatImgUrl = Util.jsonToString(json['wxHeadUrl']);

        // Handle candidate organization
        profile.candidateOrg = json['userOrg'] == null
            ? null
            : MerchantCandidateMgr.fromJson(json['userOrg']);

        // 测试权限
        if (TestConfig.simPermissionTest) {
            profile._permissionMgr = (new TestSimulateData()).simulatePermissionInfoWithAllPermission();
        }

        return profile;
    }

    async setOrg(org) {
        let retStr = '';
        try {
            this._org = org;

            const values = await Promise.all([
                this.getAccountOrgJoinData(org.orgId, this.id, this.token),
                this.getMerchantActivePkg(org),
                this.getMerchantPublicStore(org),
                this.getDefaultCustomerAndSupplier(org),
                this.getCustomFundAccountType(org),
            ]);

            // console.log(' setOrg 获取商户信息', values);

            if (values[0]) return values[0];
            if (values[1]) return values[1];
            if (values[2]) return values[2];
            if (values[4]) return values[4];

            const additionalValues = await Promise.all([
                this.getOrgSettings(),
                this.getOrgRetailSettings(),
            ]);

            if (additionalValues[0]) return additionalValues[0];
            if (additionalValues[1]) LogUtil.v(additionalValues[1]);

            const profilePermission = await this.getProfilePermission(org);
            if (profilePermission) retStr += profilePermission;

            return retStr || null;
        } catch (e) {
            console.error('Error in setOrg:', e);
            return "获取商户信息失败";
        }
    }

    /// 获取商户与账户关联信息
    async getAccountOrgJoinData(orgId, accountId) {
        const netWorkData = await getAccountOrgJoinData(orgId, accountId);
        const apiData = NetworkParser.parseNetworkResult(netWorkData, AccountOrgJoinData.fromJson);;
        if (apiData.data) {
            const joinData = apiData.data;
            if (!joinData.id) {
                return '无组织关联信息';
            }
            if (!joinData.whetherCanLogin) {
                return '未授权访问组织信息';
            }
            if (!joinData.enabled) {
                return '该账号被组织禁用';
            }
            return null;
        }
        return apiData.resErr || '获取组织关联信息未知错误';
    }

    /// 获取商户有效套餐
    async getMerchantActivePkg(org) {
        const netWorkData = await getMerchantOrgActivePackageInfo(org.orgId);

        const apiData = NetworkParser.parseNetworkResult(netWorkData, MerchantActivePackage.fromJson);

        if (apiData.data) {
            org.activePkg = apiData.data;
            if (!org.activePkg.package.id) {
                return '无商户授权套餐信息，请联系客服人员';
            }
            //  测试数据
            if (TestConfig.simPermissionTest) {                
                org.orgPermissionInfo = (new TestSimulateData()).simulatePermissionInfoWithAllPermission();
            } else {
                org.orgPermissionInfo = org.activePkg.package.permissionInfo;;
            }
            return null;
        }
        return apiData.resErr || '获取有效套餐信息未知错误';
    }

    /// 获取商户公共门店
    async getMerchantPublicStore(org) {
        const netWorkData = await getPublicStore(org.orgId);
        const apiData = NetworkParser.parseNetworkResult(netWorkData, Store.fromJson);
        if (apiData.data) {
            org.publicStore = apiData.data;
            return null;
        }
        return '获取公共资源信息失败';
    }

    /// 获取零售客户和零散供应商
    async getDefaultCustomerAndSupplier(org) {
        const filter = new TargetObjectFilter();
        filter.objPlatformType = TargetObjectPlatformType.TPlatformCreated;


        // todo 这里面没有传入 api 接口函数
        const apiData = await getApiData(TargetObject.fromJson, org.orgId, new DataPage(0, 0, Definition.gDefualPageSize), getTargetObjectData, filter.toJson());
        if (apiData.data) {
            const [objA, objB] = apiData.data.dataList;
            if (objA.platformType === TargetObjectPlatformType.TPlatformCreated && objB.platformType === TargetObjectPlatformType.TPlatformCreated) {
                if (objA.objType === TargetObjectType.TCustomer && objB.objType === TargetObjectType.TSupplier) {
                    org.defaultCustomer = objA;
                    org.defaultSupplier = objB;
                } else if (objA.objType === TargetObjectType.TSupplier && objB.objType === TargetObjectType.TCustomer) {
                    org.defaultCustomer = objB;
                    org.defaultSupplier = objA;
                }
            }
        }
        return null;
    }

    /// 获取贵金属等自定义货币账户类型
    async getCustomFundAccountType(org) {

        let fundUiAction = new FundUiAction();
        let res = await fundUiAction.getSelfFundAccountTypeData({
            orgId: org.orgId,
            pageInfo: new DataPage(1, 0, 100)
        });

        if (res && res.data && res.data.dataList) {
            org.customerFundAccountTypeList = res.data.dataList;
            console.log('获取自定义支付类型列表成功', res.data.dataList)
        } else if (res.resErr) {
            console.error('获取自定义支付类型列表失败', res.resErr)
            return '获取自定义支付类型列表失败';
        }

        return null;
    }

    /// 获取登录商户设置
    async getOrgSettings() {
        /* todo 模拟数据
        if (TestConfig.orgSettingsTest) {
            Engine.setOrgSetting(TestSimulateData.simOrgSettingsConfig());
            return null;
        } else 
        */
        {
            const netWorkData = await getOrgSettings(this._org.orgId);
            const apiData = NetworkParser.parseNetworkResult(netWorkData, OrgSettings.fromJson);
            if (apiData.data) {
                Engine.setOrgSetting(apiData.data);
                return null;
            }
            else if (apiData.resErr == "服务器返回空数据") {
                // 新建商户没有该配置，采用默认配置
                Engine.setOrgSetting(new OrgSettings());
                return null;
            }
            return apiData.resErr || '加载配置参数失败';
        }
    }

    /// 获取登录商户零售设置
    async getOrgRetailSettings() {
        /* todo 模拟数据
        if (TestConfig.retailSettingsTest) {
            Engine.setRetailSetting(new MerchantRetailSettings());
            return null;
        } else
        */
        {
            const netWorkData = await getRetailSettings(this.org.orgId);
            const apiData = NetworkParser.parseNetworkResult(netWorkData, MerchantRetailSettings.fromJson);
            if (apiData.data) {
                Engine.setRetailSetting(apiData.data);
                return null;
            }
            return apiData.resErr || '加载配置参数失败';
        }
    }

    /// 获取登录账号权限
    async getProfilePermission(org) {
        const netWorkData = await getEmployeeDetailInfo(this.id, org.orgId);
        const apiData = NetworkParser.parseNetworkResult(netWorkData, Employee.fromJson);
        if (apiData.data) {
            let ret = await this._setPermission(apiData.data, org);

            if (ret != null) {

                // 出错返回
                return ret;
            }
        }
        else if (apiData.resErr) {
            // 出错            
            return apiData.resErr || '获取访问权限未知错误';
        }

        // 商户主判断，商户主没有设置权限，但是有商户的所有权限
        if ((this.id && this.id === org.owner) || TestConfig.getFullOrgPermission) {
            this._permissionMgr = PermissionInfo.clone(this._org.orgPermissionInfo);
            return null;
        }

        return null;
    }

    /// 赋值Employee权限
    async _setPermission(employee, org) {
       // console.log("---> profile set permission");
        // Step 1: 合并不同角色的 fCodeList
        let fCodeList = [];
        employee.role.forEach(role => {
            role.fCodeList.forEach(item => {
                if (!fCodeList.includes(item)) {
                    fCodeList.push(item);
                }
            });
        });

        // Step 2: 初始化权限
        let menuTree = PermissionInfo.clone(Engine.profile.org.orgPermissionInfo).menuTree;

        let pInfo = new PermissionInfo();
        menuTree.forEach(item => {
            if (item.clearUnselectedNode(fCodeList)) {
                pInfo.menuTree.push(item);
            }
        });

        pInfo.initFunctionMenuPermissionMap();
        pInfo.getLeafTreeNode(fCodeList);
        this._permissionMgr = pInfo;

        if (TestConfig.simPermissionTest) {
            // 开启模拟权限，普通员工登录也使用模拟权限
            // 暂时不开启，因为 org 的权限还么有设置， todo org 权限好了之后再处理
           // this._permissionMgr = (new TestSimulateData()).simulatePermissionInfoWithAllPermission();
        }

        // Step 3: 门店访问权限
        if (!Engine.getOrgSettings().multiStoreMode) {
            // 非多门店版，所有用户当前store为publicStore
            this.currentStore = org.publicStore;
        } else {
            // 访问所有权限
            this.accessAllStoreData = employee.accessAllStoreData;
            this.accessAllStoreData = employee.accessAllWarehouseData;

            // 门店信息从 employee 授权商店处获取
            //  如果是访问所有门店，后续代码会获取所有门店列表
            // 如果是访问所有门店，则需要请求所有门店列表
            this._storeList = [];
            if (this.accessAllStoreData) {
                let ret = await this.getAllStoreList(org);
                if (ret) {
                    return ret; // 如果获取门店列表失败，返回错误信息
                }
            } else {
                this._storeList = [...employee.storeRelationList];
            }

            if (this.accessAllStoreData) {
                this._storeList.unshift(
                    new StoreEmployeeRelation({
                        id: '',
                        store: new Store({ id: '0', name: '所有门店' }),
                        employee: new Employee()
                    })
                );
            }

            // 当前访问门店
            // currentStore id = "0" 表示选择访问所有资源
            if (this.currentStore && this.currentStore.id !== '0') {
                let newCurrentStore = this._storeList.filter(element => element.store.id === currentStore.id);
                if (newCurrentStore.length === 0) {
                    this.currentStore = null; // 如果授权变更后没有匹配的门店，则清空当前访问门店
                } else {
                    this.currentStore = newCurrentStore[0].store;
                }
            } else if (this.currentStore && this.currentStore.id === '0') {
                // 清空访问门店（如果仍然是访问所有门店，后续代码会重新赋值）
                this.currentStore = null;
            }

            if (!this.currentStore) {
                if (this.accessAllStoreData) {
                    this.currentStore = this._storeList[0].store;
                } else {
                    let publicStore = this._storeList.find(element => element.store.publicStore);
                    if (publicStore) {
                        this.currentStore = publicStore.store;
                    } else if (this._storeList.length > 0) {
                        this.currentStore = this._storeList[0].store;
                    } else {
                        // 如果都没有授权，则默认为 public store, 兼容老数据
                        this.currentStore = org.publicStore;
                    }
                }
            }
        }

        return null;
    }

    /// 获取所有门店列表信息
    async getAllStoreList(org) {
        let storeList = [];
        /* todo 模拟数据
        if (TestConfig.storeTest) {
            await new Promise(resolve => setTimeout(resolve, 100));
            storeList = TestSimulateData.simStoreData();
        } else 
        */
        {
            const netWorkData = await getAllStoreList(this.org.orgId, { enabled: 1 });
            const apiData = NetworkParser.parseNetworkResut(netWorkData, null);
            if (apiData.data) {
                storeList = apiData.data.map(item => Store.fromJson(item));
            } else {
                return `获取门店列表错误: ${apiData.resErr}`;
            }
        }
        this._storeList = storeList.map(item => new StoreEmployeeRelation('', item, new Employee(this.id)));
        return null;
    }

}
